package sorter;

import java.rmi.Naming;
import java.util.Observable;
import java.util.Observer;

public class ListJoiner implements Observer
{
	private int ThreadNumber = 0;
	private int addCounter = 0;
	private Comparable[][] lists;
	Comparable[] lst;
	private int listValue;
	private long time;
	private long timeTook;
	
	/**
	 * Constructor of the class ListJoiner
	 * @param i
	 * @param j
	 */
	public ListJoiner(int i, int j, long t)
	{
		listValue = i;
		lst = new Comparable[j];
		lists = new Comparable[listValue][];
		time = t;
	}
	
	/**
	 * Getter for the ThreadNumber
	 * @return ThreadNumber
	 */
	public int getThreadNumber()
	{
		return ThreadNumber;
	}
	
	/**
	 * Function that makes one comparable arraylist of multiple ones stored in an arraylist.
	 * Afterwards calls the print function
	 * @throws NullPointerException
	 */
	public void join() throws NullPointerException
	{
		int counter = 0;
		for(int j = 0; j <lists.length; j++)
		{
			for(int i = 0; i< lists[j].length; i++)
			{
				lst[counter] = lists[j][i];
				counter++;
			}
		}
		timeTook = System.currentTimeMillis() - time;
		printJoinedList();
	}

	/**
	 * Function to print the joined arraylist
	 */
	public void printJoinedList()
	{
		for(int i = 0; i< lst.length; i++)
		{
			System.out.println(lst[i]);
		}
		System.out.println("------------------------");
		double t = (double)timeTook;
		System.out.println("It took: "+ t/1000+"s to sort.");
	}
	
	/**
	 * Function to add an comparable arraylist in an arraylist on a given location
	 * @param c the comparable arraylist
	 * @param TN threadnumber
	 */
	public void makeCompList(Comparable[] c, int TN)
	{
		lists[TN] = c;
	}

	/**
	 * Update function of the observable, calls for function within this class
	 */
	@Override
	public void update(Observable o, Object arg) 
	{
		int temp = ((SorterThread) o).getThreadNumber();
		Comparable[] C = ((SorterThread) o).getList();
		makeCompList(C, temp);
		addCounter++;
		if(addCounter==lists.length)
		{
			join();
		}
	}
	
}
